<script setup lang="ts">
import { h, ref } from 'vue';
import type { DataTableColumns, DataTableRowKey } from 'naive-ui';
import { NButton, NPopconfirm } from 'naive-ui';
import { deleteUser, getUserList } from '@/service/api';
import UseTable from '@/components/table/use-table.vue';
import type { FormItemProps, FormProps } from '@/components/form/props';
import Drawer from './modules/drawer.vue';

const formItems: FormItemProps[] = [
  {
    label: '用户名',
    path: 'username',
    component: 'input',
    componentProps: {
      placeholder: '请输入用户名'
    },
    grid: {
      span: 6
    }
  }
];
const formConfig: FormProps = {
  formItems,
  labelPlacement: 'left',
  modelValue: {
    name: ''
  },
  rules: {},
  size: 'medium',
  labelWidth: 80,
  inline: true,
  formGrid: {
    span: 18
  }
};

const getColumn: DataTableColumns<{ id: string | number; name: string }> = [
  {
    type: 'selection',
    width: 60
  },
  {
    title: 'ID',
    key: 'id',
    width: 80
  },
  {
    title: '名称',
    key: 'username'
  },
  {
    title: '角色',
    key: 'permissions',
    render: (row: any) => {
      return row.permissions.map((item: any) => item.name).join(',');
    }
  },
  {
    title: '操作',
    key: 'operation',
    align: 'center',
    render: (row: any) => {
      const deleteBtn = h(
        NPopconfirm,
        {
          onConfirm: () => handleDelete([row.id]),
          trigger: 'click'
        },
        {
          // 关键修改：将插槽内容用函数包裹
          trigger: () =>
            h(
              NButton,
              {
                type: 'error',
                ghost: true,
                size: 'small'
              },
              () => '删除' // 文本内容也用函数返回
            ),
          default: () => '确定要删除这条数据吗？' // 内容插槽同样用函数包裹
        }
      );
      return h('div', {}, [
        h(
          NButton,
          { class: 'mr-2', type: 'primary', ghost: true, size: 'small', onClick: () => handleMyEdit(row) },
          { default: () => '编辑' }
        ),
        deleteBtn
      ]);
    } // 会在模板中用slot覆盖
  }
];

const drawerRef = ref<InstanceType<typeof Drawer>>();
const tableRef = ref<InstanceType<typeof UseTable>>();

function batchDeleteApi(params: DataTableRowKey[]) {
  // 定义为 Promise<{ success: boolean }> 类型的数组
  const arr: Promise<unknown>[] = [];
  params.forEach(item => {
    arr.push(deleteUser({ id: item as number }));
  });
  return Promise.all(arr);
}

async function handleDelete(params: DataTableRowKey[]) {
  await deleteUser({ id: params[0] as number });
}

function handleMyEdit(row: Api.System.User) {
  const { id, username, permissions = [] } = row;
  drawerRef.value?.openDrawer({
    title: '编辑',
    id,
    username,
    roleIds: permissions.map(item => item.id),
    password: '',
    reenteredPassword: ''
  });
}

function handleAdd() {
  drawerRef.value?.openDrawer({ title: '新增', id: 0, username: '', roleIds: [], password: '', reenteredPassword: '' });
}

function afterLeave() {
  tableRef.value?.refreshList();
}
</script>

<template>
  <div>
    <UseTable
      ref="tableRef"
      :batch-delete-api="batchDeleteApi"
      :get-table-data-api="getUserList"
      :table-columns="getColumn"
      title="用户列表"
      :form-config="formConfig"
      @add="handleAdd"
    />

    <Drawer ref="drawerRef" @after-leave="afterLeave" />
  </div>
</template>

<style scoped></style>
